import Router from "koa-router";
import serviceContent from "../../service/content/index.js";
import serviceModel from "../../service/model/index.js";

import response from "../../response.js";
import _ from "lodash";
const router = new Router();
function transform(value) {
  if (typeof value === "string") {
    return value;
  }
  if (typeof value === "number") {
    return value;
  }
  if (typeof value === "object") {
    return JSON.stringify(value);
  }
  return "";
}
// function transformValue(value) {

//   return JSON.parse(value);
// }
router.post("/", async (ctx) => {
  try {
    const data = ctx.data || {};
    const { modelId } = data;
    const contents = [];
    Object.keys(data).forEach((key) => {
      if ("modelId" !== key) {
        const item = data?.[key];
        contents.push({
          key,
          fieldId: item?.id,
          value: transform(item?.value),
        });
      }
    });
    const modelResult = serviceModel.findById(modelId);
    if (!modelResult) {
      ctx.body = response.fail({ msg: `${modelId} not in data` });
      return;
    }
    const saveData = contents.map((item) => {
      return [item?.value, modelId, item?.fieldId];
    });
    const result = await serviceContent.save(saveData);
    if (!result) {
      ctx.body = response.fail({ msg: "fail" });
    } else {
      ctx.body = response.success({ msg: "success" });
    }
  } catch (e) {
    console.error(e);
    ctx.body = response.fail({ msg: "fail" });
  }
});
router.get("/list", async (ctx) => {
  try {
    const list = await serviceContent.getList();
    ctx.body = response.success({ data: { list: list } });
  } catch (e) {
    console.error(e);
    ctx.body = response.fail({ msg: "fail" });
  }
});
router.get("/:id", async (ctx) => {
  try {
    const { id } = ctx.params || {};
    if (_.isNil(id)) {
      ctx.body = response.fail({ msg: "id not empty" });
      return;
    }
    const row = await serviceContent.getDetails(id);
    console.log(row);
    if (!row) {
      ctx.body = response.fail({ msg: "fail" });
    } else {
      ctx.body = response.success({
        data: {
          modelId: Number(id),
          list: row.map((item) => {
            return { ...item, value: item?.value };
          }),
        },
      });
    }
  } catch (e) {
    console.error(e);
    ctx.body = response.fail({ msg: "fail" });
  }
});

export default router;
